let arrId = 0;
let canvas = document.getElementById("ourCanvas");
let width = $(window).width();
let height = $(window).height();
let scale = window.devicePixelRatio;
let Dom = {
    preload: $(".preload"),
    finishBtn: $(".finish-btn"),
    footWrap: $('.foot-wrap'),
    drawWarp: $("#drawWarp"),
    percent: $(".percent"),
    screen: $('#screen1'),
    start: $('#screen2')
};
let id = 'XXX';

let downheight, ishide = false;
let imgindex = 0;
let fileList = [
    'assets/Room.jpg',
    'assets/last-page.jpg',
    'assets/icon_ui/hand.gif',
    'assets/icon_ui/icon_camera.jpg',
    'assets/icon_ui/remove.e80f2.png',
    'assets/icon_ui/resize.65162.png',
    'assets/icon_ui/unfold.jpg',
    'assets/icon_ui/long-press-btn.png',
    'assets/icon_ui/photoShare.jpg',
    'assets/icon_ui/type_girl.png',
    'assets/icon_ui/type_boy.png',
    'assets/icon_ui/type_face.png',
    'assets/icon_ui/type_summer.png',
    'assets/icon_ui/type_winter.png',
    'assets/icon_ui/type1.png',
    'assets/icon_ui/type1-cur.png',
    'assets/icon_ui/type2.png',
    'assets/icon_ui/type2-cur.png',
    'assets/icon_ui/type3.png',
    'assets/icon_ui/type3-cur.png',
    'assets/icon_ui/type4.png',
    'assets/icon_ui/type4-cur.png',
    'assets/icon_ui/type5.png',
    'assets/icon_ui/type5-cur.png',
    'assets/icon_ui/back-btn.png',
    'assets/icon_screen/fan.gif',

    'assets/icon_boy/boy1.png',
    'assets/icon_boy/boy2.png',
    'assets/icon_boy/boy3.png',
    'assets/icon_boy/boy4.png',
    'assets/icon_boy/boy5.png',
    'assets/icon_boy/boy6.png',

    'assets/icon_girl/girl1.png',
    'assets/icon_girl/girl2.png',
    'assets/icon_girl/girl3.png',
    'assets/icon_girl/girl4.png',
    'assets/icon_girl/girl5.png',
    'assets/icon_girl/girl6.png',
    'assets/icon_girl/girl7.png',

    'assets/icon_summer/summer1.png',
    'assets/icon_summer/summer2.png',
    'assets/icon_summer/summer3.png',
    'assets/icon_summer/summer4.png',
    'assets/icon_summer/summer5.png',
    'assets/icon_summer/summer6.png',
    'assets/icon_summer/summer7.png',
    'assets/icon_summer/summer8.png',
    'assets/icon_summer/summer9.png',
    'assets/icon_summer/summer10.png',
    'assets/icon_summer/summer11.png',

    'assets/icon_winter/winter1.png',
    'assets/icon_winter/winter2.png',
    'assets/icon_winter/winter3.png',
    'assets/icon_winter/winter4.png',
    'assets/icon_winter/winter5.png',
    'assets/icon_winter/winter6.png',
    'assets/icon_winter/winter7.png',
    'assets/icon_winter/winter8.png',
    'assets/icon_winter/winter9.png',
    'assets/icon_winter/winter10.png',
    'assets/icon_winter/winter11.png',
    'assets/icon_winter/winter12.png',
    'assets/icon_winter/winter13.png',

    'assets/icon_type3/type3-1.png',
    'assets/icon_type3/type3-2.png',
    'assets/icon_type3/type3-3.png',
    'assets/icon_type3/type3-4.png',
    'assets/icon_type3/type3-5.png',
    'assets/icon_type3/type3-6.png',
    'assets/icon_type3/type3-7.png',
    'assets/icon_type3/type3-8.png',
    'assets/icon_type3/type3-9.png',
    'assets/icon_type3/type3-10.png',
    'assets/icon_type3/type3-11.png',
    'assets/icon_type3/type3-12.png',
    'assets/icon_type3/type3-13.png',
    'assets/icon_type3/type3-14.png',
    'assets/icon_type3/type3-15.png',
    'assets/icon_type3/type3-16.png',
    'assets/icon_type3/type3-17.png',
    'assets/icon_type3/type3-18.png',
    'assets/icon_type3/type3-19.png',
    'assets/icon_type3/type3-20.png',
    'assets/icon_type3/type3-21.png',
    'assets/icon_type3/type3-22.png',
    'assets/icon_type3/type3-23.png',
    'assets/icon_type3/type3-24.png',
    'assets/icon_type3/type3-25.png',
    'assets/icon_type3/type3-26.png',
    'assets/icon_type3/type3-27.png',
    'assets/icon_type3/type3-28.png',
    'assets/icon_type3/type3-29.png',
    'assets/icon_type3/type3-30.png',
    'assets/icon_type3/type3-31.png',
    'assets/icon_type3/type3-32.png',
    'assets/icon_type3/type3-33.png',
    'assets/icon_type3/type3-34.png',
    'assets/icon_type3/type3-35.png',
    'assets/icon_type3/type3-36.png',
    'assets/icon_type3/type3-37.png',
    'assets/icon_type3/type3-38.png',
    'assets/icon_type3/type3-39.png',
    'assets/icon_type3/type3-40.png',
    'assets/icon_type3/type3-41.png',
    'assets/icon_type3/type3-42.png',
    'assets/icon_type3/type3-43.png',
    'assets/icon_type3/type3-44.png',
    'assets/icon_type3/type3-45.png',
    'assets/icon_type3/type3-46.png',
    'assets/icon_type3/type3-47.png',
    'assets/icon_type3/type3-48.png',
    'assets/icon_type3/type3-49.png',
    'assets/icon_type3/type3-50.png',
    'assets/icon_type3/type3-51.png',
    'assets/icon_type3/type3-52.png',

    'assets/icon_type4/type4-1.png',
    'assets/icon_type4/type4-2.png',
    'assets/icon_type4/type4-3.png',
    'assets/icon_type4/type4-4.png',
    'assets/icon_type4/type4-5.png',
    'assets/icon_type4/type4-6.png',
    'assets/icon_type4/type4-7.png',
    'assets/icon_type4/type4-8.png',
    'assets/icon_type4/type4-9.png',
    'assets/icon_type4/type4-10.png',
    'assets/icon_type4/type4-11.png',
    'assets/icon_type4/type4-12.png',
    'assets/icon_type4/type4-13.png',
    'assets/icon_type4/type4-14.png',
    'assets/icon_type4/type4-15.png',
    'assets/icon_type4/type4-16.png',
    'assets/icon_type4/type4-17.png',

    'assets/icon_type5/type5-1.png',
    'assets/icon_type5/type5-2.png',
    'assets/icon_type5/type5-3.png',
    'assets/icon_type5/type5-4.png',
    'assets/icon_type5/type5-5.png'
];

lazyLoad = () => {
    $(".lazyLoad").forEach(function (e) {
        $(e).attr('src', $(e).attr('data-src'));
    });
};

$('#screen1 .skip').on("touchend", function () {
    Dom.preload.hide();
    $("#wrapper2,#wrapper3,#wrapper4,#wrapper5").hide();
    Dom.screen.hide().removeClass('fadeIn');
    $('#wrap').find('.wrap-cap').show();
});

$(".start-btn").on("touchend", function () {
    $("#wrapper2,#wrapper3,#wrapper4,#wrapper5").hide();
    Dom.preload.addClass("fadeOut");
    Dom.preload[0].addEventListener('webkitAnimationEnd', function () {
        $(this).remove();
        $('#wrap').find('.wrap-cap').show();
    });
});

window.onload = function () {

    imgLoader(fileList, res => {
        res = parseInt(res * 100);
        Dom.percent.html(`${res}%`);
        if (100 === res) {
            setTimeout(() => {
                lazyLoad();
                Dom.percent.hide();
                Dom.screen.addClass('fadeIn animated');
                Dom.screen.on('webkitAnimationEnd', function(){
                    Dom.preload.hide();
                    InitCanvas();
                });
            }, 400);
        }
    });

    downheight = parseInt($(".tabs-wrap").height() - $(".foot-wrap").height());

    let myScroll1 = new IScroll('#wrapper1', {
        mouseWheel: true,
        useTransition: false,
        click: true
    });
    let myScroll2 = new IScroll('#wrapper2', {
        mouseWheel: true,
        useTransition: false,
        resizeScrollbars: true,
        click: true
    });
    let myScroll3 = new IScroll('#wrapper3', {
        mouseWheel: true,
        useTransition: false,
        click: true
    });
    let myScroll4 = new IScroll('#wrapper4', {
        mouseWheel: true,
        useTransition: false,
        click: true
    });
    let myScroll5 = new IScroll('#wrapper5', {
        mouseWheel: true,
        useTransition: false,
        click: true
    });

    //screen
    let sort = 0;
    Dom.screen.on('webkitAnimationEnd', function(){
        setTimeout( () => {
            Dom.screen.children('.eye').addClass('blink');
        }, 500);
    });
    Dom.screen.children('.eye').on('webkitAnimationEnd', function () {
        $(this).hide().siblings('.word1').addClass('fadeIn animated show');
    });
    Dom.screen.children('.word1').on('webkitAnimationEnd', function(e){
        e.stopPropagation();
        if(sort === 0){
            sort = 1;
            $(this).children('.fonts').addClass('fadeIn animated show');
        }
        else if(sort === 3){
            sort = 4;
            $(this).removeClass('fadeOut animated show')
                .siblings('.word2').addClass('fadeIn animated show');
        }
    });
    Dom.screen.children('.word2').on('webkitAnimationEnd', function (e) {
        e.stopPropagation();
        if(sort === 4){
            sort = 5;
            $(this).append('<img src="./assets/icon_screen/fan.gif" class="fan abso lazyLoad">');
            $(this).children('.fonts').addClass('fadeIn animated show');
        }
        else if (sort === 6) {
            sort = 7;
            $(this).removeClass('fadeOut animated show')
                .siblings('.word3').addClass('fadeIn animated show');
        }
    });
    Dom.screen.children('.word3').on('webkitAnimationEnd', function (e) {
        e.stopPropagation();
        if(sort === 7){
            sort = 8;
            $(this).children('.fonts').addClass('fadeIn animated show')
                .siblings('.ball').addClass('fadeIn animated show');
        }
    });
    Dom.start.on('webkitAnimationEnd', function (e) {
        e.stopPropagation();
        if(sort === 11){
            sort = 12;
            $(this).hide().removeClass('fadeOut animated');
            $('#wrap').find('.wrap-cap').show();
        }
    });

    Dom.screen.children('.word3').children('.ball').on('webkitAnimationEnd', function () {
        if(sort === 8){
            sort = 9;
            $(this).siblings('.fonts').removeClass('fadeIn animated')
                .addClass('fadeOut animated');
            $(this).removeClass('fadeIn animated').addClass('jump animated');
            Dom.screen.children('.skip').addClass('fadeOut animated show');
        }
    });
    Dom.screen.children('.word1').children('.fonts').on('webkitAnimationEnd', function () {
        if(sort === 1){
            sort = 2;
            $(this).removeClass('fadeIn animated').addClass('fadeOut animated')
                .siblings('.animal').addClass('chan animated show');
        }
    });
    Dom.screen.children('.word1').children('.animal').on('webkitAnimationEnd', function () {
        if(sort === 2){
            sort = 3;
            $(this).hide().removeClass('chan animated show')
                .parent('.word1').removeClass('fadeIn animated show').addClass('fadeOut animated show');
        }
    });
    Dom.screen.children('.word2').children('.fonts').on('webkitAnimationEnd', function () {
        if (sort === 5) {
            sort = 6;
            $(this).parent('.word2').removeClass('fadeIn animated').addClass('fadeOut animated show');
        }
    });
    Dom.screen.children('.skip').on('webkitAnimationEnd', function () {
        if (sort === 9) {
            sort = 10;
            $(this).hide().removeClass('fadeOut animated show');
            Dom.screen.removeClass('fadeIn animated').hide()            
                .children('.word3').removeClass('fadeIn animated show');
            Dom.start.show()
                .children('button').addClass('fadeInUp animated');
        }
    });
    Dom.start.children('button').on('touchend', function(){
        if(sort === 10){
            sort = 11;
            $("#wrapper2,#wrapper3,#wrapper4,#wrapper5").hide();
            Dom.start.addClass('fadeOut animated');
        }
    });
    $(".scroller button").on("click", function () {
        let thisIndex = $(this).index();
        $(this).addClass('cur').siblings('button').removeClass('cur');
        $(this).parent().siblings('.wrap-list').find('ul').eq(thisIndex).show().siblings('ul').hide();
        if ($(this).parents('.scroll-wrap').attr('id') == 'wrapper1') {
            myScroll1.refresh();
        } else {
            myScroll2.refresh();
        }
    });

};

$(".type").click(function () {
    $(this).addClass("curr").siblings().removeClass("curr");
    $(".scroll-wrap").hide().eq($(this).index()).show();

    if ($(".close-tabs").hasClass("down")) {
        $(".close-tabs").removeClass("down");
        $('.wrap-cap').removeClass('slide-down');
        Dom.footWrap.css("bottom", "0");
    }
});

$(".close-tabs").click(function () {
    if ($(this).hasClass("down")) {
        $(this).removeClass("down");
        $(this).parent('.wrap-cap').removeClass('slide-down');
        Dom.footWrap.css("bottom", "0");
    }
    else {
        $(this).addClass("down");
        $(this).parent('.wrap-cap').addClass('slide-down');
        Dom.footWrap.css("bottom", downheight + "px");
    }
});

$(".roombg").on("touchstart", function (ev) {
    removeBorder();
});

let spriteUrl = 'icon_girl';
$(".scroller li").on("click", function () {
    let ZIndex = $(this).attr("data-zindex");
    let spriteID = $(this).children('img').attr("data-src");

    let _index = $(this).parent().index();
    let num = $(this).parents('.scroll-wrap').index() + 1;
    if ($(this).parents('.scroll-wrap').attr('id') == 'wrapper1'){
        if (_index === 0){
            spriteUrl = 'icon_girl';
        }
        else if (_index === 1) {
            spriteUrl = 'icon_boy';
        }
        else{
            spriteUrl = 'icon_face';
        }
    }
    else if ($(this).parents('.scroll-wrap').attr('id') == 'wrapper2') {
        if (_index === 0) {
            spriteUrl = 'icon_summer';
        } else {
            spriteUrl = 'icon_winter';
        }
    }
    else{
        spriteUrl = `icon_type${num}`;
    }


    removeBorder();
    addIconToRoom(spriteUrl, spriteID, ZIndex);
    arrId++;

});

$(document).on('touchstart', '.img_box', function () {
    removeBorder();
    $(this).addClass("border-outer");
});

$(document).on("touchend", '.remove-btn', function (ev) {
    ev.stopPropagation();
    $(this).parent(".img_box").remove();
    arrId--;
});

$(".finish-btn").on("touchend", function () {
    removeBorder();
    $(".wrap-cap,.foot-wrap").hide();
    $('.shareBanner').prepend(`<span>你是第<i>${id}</i>位</span>`);
    $('.shareBanner').addClass('show');
    
    let options = {};
    options.scale = scale;
    options.width = width;
    options.height = height;
    options.canvas = canvas;
    options.useCORS = true;
    options.logging = false;
    
    setTimeout(function() {
        html2canvas($("#wrap")[0], options)
            .then(function (canvas) {
                imgData = canvas.toDataURL("image/jpg");
                sessionStorage.setItem("imgData", imgData);
                $("#finalDesk").attr("src", imgData);
                showEndPage();
            });
    },300);
});

// $(".back-btn").on("touchend", function () {
//     Dom.drawWarp.show();
//     $(".finish-btn,.foot-wrap").show();
//     $(".foot-share img,.end-page,.save-tishi").hide();
//     $("#finalDesk").attr("src", '');
//     let ctx = canvas.getContext("2d");
//     ctx.clearRect(0, 0, canvas.width, canvas.height);
// });

function showEndPage() {
    setTimeout(function () {
        $(".end-page").show();
        $("body").removeClass("noselect");
        $(".btn-block")[0].addEventListener("webkitAnimationEnd", function () {
            $(this).removeClass("fadeInUp").addClass("clickAni");
        });
    }, 300);
}

function InitCanvas() {
    canvas.width = width * scale;
    canvas.height = height * scale;
    canvas.style.width = width + "px";
    canvas.style.height = height + "px";
    let context = canvas.getContext("2d");
    context.scale(scale, scale);
}

function addIconToRoom(spriteurl, spriteid, zindex) {
    let _src = spriteid;
    let _imgId = spriteurl + arrId;
    let _str = `<p id="${_imgId}" class="img_box border-outer" style="z-index:${zindex};"><i class="remove-btn"></i><i class="icon_scale"></i><img src=${_src}></p>`;
    let _tishi = `<img src="assets/icon_ui/hand.gif" id="icon_hand" style="position: absolute;width:2.4rem;left:50%;margin-left:-1.2rem;top: 46%;z-index: 999; ">`;

    let _newImg = new Image();
    _newImg.src = _src;
    _newImg.onload = function () {
        $("#drawWarp").append(_str);
        if (!ishide) {
            $("#drawWarp").append(_tishi);
            ishide = true;
            setTimeout(function () {
                document.getElementById('icon_hand').style.display = "none";
            }, 1500);
        }
        let el = document.getElementById(_imgId);
        let pwidth = _newImg.width / 40,
            pheight = _newImg.height / 40;

        $(document).find("#" + _imgId).css({
            "opacity": 1,
            "width": pwidth + "rem",
            "height": pheight + "rem",
            "marginLeft": pwidth * -0.5 + "rem",
            "marginTop": pheight * -0.5 + "rem"
        });

        setTimeout(function () {
            Transform(el);
            let initScale = 1;
            let gesture = new AlloyFinger(el, {
                rotate: function (evt) {
                    //el.rotateZ += evt.angle;
                },
                pinchStart: function () {
                    initScale = el.scaleX;
                    let ozIndex = el.getAttribute("z-index");
                    el.style.zIndex = parseInt(ozIndex)+1;
                },
                pinch: function (evt) {
                    el.scaleX = el.scaleY = initScale * evt.zoom;
                },
                pressMove: function (evt) {
                    el.translateX += evt.deltaX;
                    el.translateY += evt.deltaY;    
                },
                tap: function (evt) {
                    let thisClass = el.className;
                    //let zIndex = parseInt(zindex.substring(1));
                    let zIndex = el.style.zIndex || 3;
                    zIndex++;
                    el.style.zIndex = zIndex;
                    //console.log(zIndex);
                    //thisClass += ` z${zIndex}`;
                    //el.className = thisClass;
                    
                    //console.log(el.scaleX + "_" + el.scaleY + "_" + el.rotateZ + "_" + el.translateX + "_" + el.translateY);
                    //console.log("tap");
                },
                doubleTap: function (evt) {
                    /*if(el.scaleX===1){
                     new To(el, "scaleX", 2, 500, ease);
                     new To(el, "scaleY", 2, 500, ease);
                     }else if(el.scaleX===2){
                     new To(el, "scaleX", 1, 500, ease);
                     new To(el, "scaleY", 1, 500, ease);
                     }*/
                },
                longTap: function (evt) {
                    //console.log("longTap");
                },
                swipe: function (evt) {
                    //console.log("swipe" + evt.direction);
                }
            });
        }, 300);
    }
}

$('.btn-block').children('.go-next').on('touchend', function () {
    $('#lastPage').addClass('show');
    $('.end-page').addClass('fadeOut').hide();
});
$('#lastPage').find('.back-btn').on('touchend', function () {
    $('#lastPage').removeClass('show');
    $('.end-page').removeClass('fadeOut').show();
});

function ease(x) {
    return Math.sqrt(1 - Math.pow(x - 1, 2));
}

function removeBorder() {
    $(document).find(".img_box").removeClass("border-outer");
}